﻿using IBll;
using IDal;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bll
{
    public class RehabilitationBll : IRehabilitationBll
    {
      
        public RehabilitationBll(IRecipeDal<Rehabilitation> recipeD,IRecipeDal<Rote> recip)
        {
            RecipeD = recipeD;
            Recip = recip;
        }

        public IRecipeDal<Rehabilitation> RecipeD { get; }
        public IRecipeDal<Rote> Recip { get; }

        public async Task<int> AddAnync(Rehabilitation rehabilitation)
        {

            string a = DateTime.Now.ToString("yyyyMMdd");
            string n = new Random().Next(100,1000).ToString();
            rehabilitation.Code = a + n;
            return await RecipeD.AddAnync(rehabilitation);


        }

        public List<Rehabilitation> GetRehabilitations()
        {

            return RecipeD.GetAllAnync().ToList();

        }

        public EmpDto ShowRehabilitation(string? name, int index, int size)
        {
            var rehabilitation = RecipeD.GetAllAnync().Where(x=>x.Isdeletable==false);
            var rote = Recip.GetAllAnync();

            var linq = from a in rehabilitation
                       join b in rote
                        on a.RoteId equals b.RoteId
                       select new {
                          a.RoteId,
                          a.RehabilitationId,
                          a.RehabilitationName,
                          a.Code,
                          a.Duration,
                          a.Num,
                          a.Price,
                          a.RehabiType,
                          b.RoteName,
                          a.Isdeletable,
                          a.IState,
                       };
            if (!string.IsNullOrEmpty(name))
            {
                linq = linq.Where(x => x.RehabilitationName.Contains(name));

            }
             int d=linq.Count();
            var h = linq.OrderBy(x => x.RehabilitationId).Skip((index - 1) * size).Take(size).ToList();
            return new EmpDto { Count = d, Mumber = h };

               



        }

        public Task<int> UpdateRageAnync(string idsting)
        {
            List<int> ides = idsting.Split(',').Select(x => Convert.ToInt32(x)).ToList();

            var ids = RecipeD.GetAllAnync().Where(x => ides.Contains(x.RehabilitationId));
             foreach (var item in ids)
            {

                item.IState = true;

            }

            return  RecipeD.UpdateRageAnync(ids.ToList());


        }

        public Task<int> UpdateState(int id)
        {

            var p = RecipeD.GetAllAnync().FirstOrDefault(x => x.RehabilitationId == id);

            if (p.Isdeletable==true)
            {
                p.Isdeletable = false;
            }
                    
             return RecipeD.UpdateAnync(p);


        }
    }
}
